import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home'
import Login from '@/views/Login'
import Users from '@/components/Users'
import List from '@/components/List'
import Rights from '@/components/Rights'
import Goods from '@/components/Goods'
import Count from '@/components/Count'
import Roles from '@/components/Roles'
import Carts from '@/components/Carts'
import Params from '@/components/Params'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      name: 'home',
      path: '/home',
      component: Home,
      children: [
        {
          name: 'users',
          path: '/users',
          component: Users
        },
        {
          name: 'list',
          path: '/list',
          component: List
        },
        {
          name: 'goods',
          path: '/goods',
          component: Goods
        },
        {
          name: 'rights',
          path: '/rights',
          component: Rights
        },
        {
          name: 'count',
          path: '/count',
          component: Count
        },
        {
          name: 'roles',
          path: '/roles',
          component: Roles
        },
        {
          name: 'carts',
          path: '/carts',
          component: Carts
        },
        {
          name: 'params',
          path: '/params',
          component: Params
        }
      ]
    },
    {
      name: 'login',
      path: '/login',
      component: Login
    }
  ]
})

// 全局路由器前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()

  const token = window.sessionStorage.getItem('token')
  if (token) return next()
  console.log('你去的不是/login路由，我得验证一下你是否登陆了')
  // console.log('to', to.path)
  // console.log('from', from.path)

  if (from.path !== '/login') router.push('/login')
})
export default router
